<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addRole(1,'0')">添加权限</el-button>
        </div>
        <!-- 表格要用树形结构,第一步转换数据为树形结构,第二table必须有row-key属性,绑定唯一标识 -->
        <el-table border :data="permissionList" row-key="id">
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="code" label="标识" />
          <el-table-column prop="description" label="描述" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addRole(2,scope.row.id)">添加</el-button>
              <el-button type="text" @click="editRole(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delRole(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 放置一个弹层 用来编辑新增节点 -->
      <el-dialog :title="isEdit?'编辑权限点':'新增权限点'" :visible="showDialog" @close="btnCancel">
        <!-- 表单 -->
        <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" style="width:90%" />
          </el-form-item>
          <el-form-item label="权限描述">
            <el-input v-model="formData.description" style="width:90%" />
          </el-form-item>
          <el-form-item label="开启">
            <el-switch
              v-model="formData.enVisible"
              active-value="1"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" type="primary" @click="addOrEdit">确定</el-button>
            <el-button size="small" @click="btnCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getPermissionListAPI, addPermissionAPI,
  getPermissionDetailAPI, updatePermissionAPI, delPermissionAPI } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
export default {
  name: 'Permission',

  data() {
    // 自定义校验规则
    const validName = (rule, value, callback) => {
      // 选出同级
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)

      // 如果点的是编辑,同时把自己排除
      if (this.isEdit) {
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      // 拿出每一项的name值,然后判断是否重复,includes方法,返回布尔值
      existNameList.map(item => item.name)
        .includes(value) ? callback(new Error(value + '已被占用')) : callback()
    }

    // 检验唯一标识
    const validCode = (rule, value, callback) => {
      // 添加时的校验：code不能重复
      let existCodeList = this.originList
      if (this.isEdit) {
        // 编辑时的校验: code不能取自己
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(it => it.code).includes(value)
        ? callback(new Error(value + '已经被占用'))
        : callback()
    }

    return {
      permissionList: [], // 权限节点列表
      showDialog: false, // 是否显示弹层
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [
          { required: true, message: '权限名称不能为空', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '权限标识不能为空', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ]
      },
      isEdit: false, // 是否为编辑,默认false
      originList: [] // 在做校验时需要用到的数据
    }
  },

  created() {
    //   调用获取权限节点方法
    this.getPermissionList()
  },

  methods: {
    // 声明获取权限节点方法
    async getPermissionList() {
      // 调用接口
      const res = await getPermissionListAPI()

      // 处理成需要的数据
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name, code }))

      // 赋值
      this.permissionList = tranListToTreeData(res.data, '0')
    },

    // 添加和编辑共用一个弹框,所以在点确认按钮之前要判断
    addOrEdit() {
      // 兜底验证
      this.$refs.perForm.validate(valid => {
        // 验证未通过
        if (!valid) return

        // 兜底验证通过,判断是编辑还是添加
        this.isEdit ? this.editPermission() : this.addPermission()
      })
    },

    // 添加角色权限
    async addPermission() {
      // 调用接口
      const res = await addPermissionAPI(this.formData)

      // 反馈用户
      this.$message.success(res.message)

      // 关闭弹窗
      this.showDialog = false

      // 重新获取数据
      this.getPermissionList()
    },

    // 编辑角色权限,(更新)
    async editPermission() {
      const res = await updatePermissionAPI(this.formData)

      // 反馈用户
      this.$message.success(res.message)

      // 关闭弹窗
      this.showDialog = false

      // 重新获取数据
      this.getPermissionList()
    },

    // 弹框关闭事件
    btnCancel() {
      // 重置编辑状态
      this.isEdit = false

      // 关闭弹框
      this.showDialog = false

      // 重置表单
      this.$refs.perForm.resetFields()

      // 重置formData
      this.formData = this.$options.data().formData
    },

    // 侧边栏添加角色
    addRole(type, pid) {
      // 展示弹框
      this.showDialog = true

      // 赋值
      this.formData.type = type
      this.formData.pid = pid
    },

    // 点编辑角色,展示弹框,数据回填
    async editRole(id) {
      // 修改isEdit状态
      this.isEdit = true

      // 调接口,传id
      const res = await getPermissionDetailAPI(id)

      // 数据回填
      this.formData = res.data

      // 展示弹框
      this.showDialog = true
    },

    // 删除角色
    async delRole(id) {
      // 确认消息弹框
      const delRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (delRes === 'cancel') return this.$message.info('已取消')

      // 调用接口，并传入 ID
      const res = await delPermissionAPI(id)

      // 反馈用户
      this.$message.success(res.message)

      // 重新获取数据
      this.getPermissionList()
    }

  }
}
</script>

<style lang="scss" scoped></style>
